/******************************************
 * Author: Dave Spadea, Spadea Enterprises, Inc.
 * Date: November 2010
 * 
 * This code is released by Spadea Enterprises, Inc for general consumption 
 * under the Apache Software License.
 * 
 */


package net.spadea.framework.messaging;

import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.Queue;

public class BrokerSubscriber extends BrokerConnection {
	
	Connection conn;
	private MessageConsumer consumer;
	
	public void connect(String url) {
		 conn = getConnection(url);
	}
	
	public void subscribe(QueueChannel channel) {

        try {
                Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue queue = sess.createQueue(channel.name);
                consumer = sess.createConsumer(queue);
        } catch(Exception e) {
                e.printStackTrace();
                System.exit(1);
        }
	}
	
	public void subscribe(TopicChannel channel) {

		try {
			Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
			Topic topic = sess.createTopic(channel.name);
			consumer = sess.createConsumer(topic);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public void subscribe(Channel channel) {
		if ( channel.getType().equals("TOPIC") )
			subscribe((TopicChannel)channel);
		else if(channel.getType().equals("QUEUE"))
			subscribe((QueueChannel)channel);
	}

	public String getMessage() {
		String message = null;
		
		try {
		        TextMessage tm = (TextMessage) consumer.receive();
		        message = tm.getText();
		} catch (Exception e) {
		        // TODO Auto-generated catch block
		        e.printStackTrace();
		        System.exit(2);
		}
		
		return message;
	}
}

